<template>
  <div>
    <AModal
      v-bind="$attrs"
      width="800px"
      :body-style="{ padding: '0px' }"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AScrollbar style="max-height: calc(100vh - 170px); overflow: auto; padding: 20px">
        <AForm ref="formRef" :model="form" auto-label-width>
          <ARow :gutter="10">
            <ACol>
              <AFormItem label="选中的销售订单">
                <ATable
                  :data="saleTableData"
                  :pagination="false"
                  :bordered="{ cell: true }"
                  :span-method="spanMethod"
                >
                  <template #columns>
                    <ATableColumn title="订单编号" data-index="saleOrderCode" :width="150">
                    </ATableColumn>
                    <ATableColumn title="产品名称" data-index="productName" :width="200">
                    </ATableColumn>
                    <ATableColumn title="规格" data-index="specModel" :width="200"> </ATableColumn>
                    <ATableColumn title="单位" data-index="unit" :width="100"> </ATableColumn>
                  </template>
                </ATable>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="qty" label="数量">
                <AInputNumber
                  v-model="form.qty"
                  model-event="input"
                  hide-button
                  :precision="0"
                  :step="1"
                ></AInputNumber>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="deliveryDate" label="交货日期">
                <ADatePicker v-model="form.deliveryDate" placeholder="交货日期" class="w100" />
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="processIdList" label="工序内容">
                <ASelect
                  v-model="form.processIdList"
                  allow-search
                  multiple
                  placeholder="输入工序内容"
                  allow-clear
                >
                  <AOption
                    v-for="(item, index) in processList"
                    :key="index"
                    :label="item.processName"
                    :value="item.processId"
                  ></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
          </ARow>
          <AFormItem field="remark" label="备注">
            <ATextarea v-model="form.remark" />
          </AFormItem>
          <ACard
            v-for="(item, index) in form.detailList"
            :key="index"
            class="card-container"
            size="small"
          >
            <template #extra>
              <ALink @click="editProduct('add')">增加材料</ALink>
              <ALink v-if="form.detailList.length > 1" @click="editProduct('del', index)">
                删除材料
              </ALink>
            </template>
            <ARow :gutter="10">
              <ACol :span="12">
                <AFormItem
                  label="生产材料"
                  :field="`detailList[${index}].materialStockId`"
                  :rules="[{ required: true, message: '请选择生产材料' }]"
                  :validate-trigger="['change', 'input', 'blur']"
                >
                  <ASelect
                    v-model="item.materialStockId"
                    allow-search
                    placeholder="输入名称进行搜索"
                    allow-clear
                    :trigger-props="{ contentStyle: { width: 'max-content' } }"
                    :filter-option="proFilter"
                    @change="changeEvent('product', item)"
                  >
                    <AOption
                      v-for="(item, index) in stockList"
                      :key="index"
                      :label="item.materialName"
                      :value="`${item.materialStockId}-${item.spec}`"
                      :disabled="detailIds.includes(`${item.materialStockId}-${item.spec}`)"
                    >
                      <div class="w100" style="line-height: 100%; margin: 6px 0px">
                        <div class="w100 erp-row-center-between">
                          <div>{{ item.materialName }}</div>
                          <ATag v-if="item.spec" color="blue">
                            {{ item.spec }}
                          </ATag>
                        </div>
                        <div
                          class="w100 erp-row-center-between"
                          style="font-size: 12px; color: #999; margin-top: 4px"
                        >
                          <span>库存数量</span>
                          <span>{{ item.stockQty }}</span>
                        </div>
                      </div>
                    </AOption>
                  </ASelect>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="qty" label="数量">
                  <AInputNumber
                    v-if="!item.outboundStatus"
                    v-model="item.qty"
                    placeholder="请输入数量"
                    :precision="0"
                    :step="1"
                    :default-value="0"
                    hide-button
                    :min="0"
                    @input="(value: any) => qtyInput(value, item)"
                  />
                  <div v-else>{{ item.qty }}</div>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem label="规格型号">
                  <div>{{ item.spec }}</div>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem label="单位">
                  <div>{{ item.unit }}</div>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem label="材质代码">
                  <div>{{ item.materialCode }}</div>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem label="压线">
                  <div>{{ item.crimpLine }}</div>
                </AFormItem>
              </ACol>
            </ARow>
          </ACard>
        </AForm>
      </AScrollbar>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import { Message, SelectOptionData } from '@arco-design/web-vue'
import {
  batchAddProductionPlan,
  getProcessAllList,
  ProcessResItem,
  ProductionPlanReq
} from '@renderer/api/productionDep'
import { SaleResItemHandle } from '@renderer/api/salesDep'
import { getStockAllList, StockResItem } from '@renderer/api/warehouseManage'
import { useMenuState } from '@renderer/store'
import { getArrayItemType } from '@renderer/types/global'

interface Props {
  [key: string]: any
  checkData: SaleResItemHandle[]
}
const props = withDefaults(defineProps<Props>(), {
  checkData: () => {
    return []
  }
})
const emit = defineEmits(['update:visible', 'reload'])
const detailIds = computed(() => form.value.detailList.map((item) => item.materialStockId))
const formRef = ref()
const form = ref<ProductionPlanReq>({
  prodPlanId: '',
  saleOrderId: '',
  productId: '',
  qty: 0,
  planProdQty: 0,
  saleOrderCode: '',
  productName: '',
  unit: '',
  prodFlowCode: [],
  processIdList: [],
  deliveryDate: '',
  remark: '',
  detailList: [
    {
      materialStockId: '',
      qty: 0,
      spec: '',
      unit: '',
      materialCode: '',
      outboundStatus: 0,
      fluteType: '',
      crimpLine: '',
      materialName: ''
    }
  ]
})
const processList = ref<ProcessResItem[]>([])
const stockList = ref<StockResItem[]>([])
const menuParam = useMenuState()
const saleTableData = ref<SaleResItemHandle[]>([])

// 获取工序列表
const getProcessList = () => {
  getProcessAllList({ processId: '' }).then((res) => {
    processList.value = res.data.list
  })
}
// 获取原材料列表
const getMaterialList = () => {
  getStockAllList({ materialName: '' }).then((res) => {
    stockList.value = res.data.list
  })
}

const editProduct = (type: 'add' | 'del', index?: number) => {
  switch (type) {
    case 'add':
      form.value.detailList.push({
        materialStockId: '',
        qty: 0,
        spec: '',
        unit: '',
        materialCode: '',
        outboundStatus: 0,
        fluteType: '',
        crimpLine: '',
        materialName: ''
      })
      break
    case 'del':
      form.value.detailList.splice(index!, 1)
      break

    default:
      break
  }
}

const changeEvent = (
  type: string,
  detailInfo: getArrayItemType<ProductionPlanReq['detailList']>
) => {
  switch (type) {
    case 'material':
      {
        const temp = stockList.value.find(
          (item) => `${item.materialStockId}-${item.spec}` === detailInfo.materialStockId
        )
        if (temp) {
          detailInfo.spec = temp.spec!
          detailInfo.unit = temp.unit!
          detailInfo.materialCode = temp.materialCode!
          detailInfo.fluteType = temp.fluteType!
        }
      }

      break

    default:
      break
  }
}

const qtyInput = (value: string, item: any) => {
  item.qty = value
}

const spanMethod = ({ record, columnIndex }) => {
  if (columnIndex < 1) {
    if (record.span) {
      console.log(record.span)
      return {
        colspan: 1,
        rowspan: record.span
      }
    }
  }
}
// 弹窗事件
const modalEvent = (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate((errors: any) => {
        if (!errors) {
          form.value.detailList.map((item) => {
            item.materialStockId = item.materialStockId?.split('-')[0]
            return item
          })
          const params: ProductionPlanReq[] = saleTableData.value.map((item) => {
            return {
              saleOrderId: item.saleOrderId,
              saleOrderCode: item.saleOrderCode,
              productId: item.productId!,
              productName: item.productName!,
              spec: item.spec,
              unit: item.unit,
              planProdQty: form.value.planProdQty,
              processIdList: form.value.processIdList,
              deliveryDate: form.value.deliveryDate,
              remark: form.value.remark,
              detailList: form.value.detailList
            }
          })

          batchAddProductionPlan(params).then(() => {
            Message.success('新增成功')
            modalEvent('cancel')
            emit('reload')
          })
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      form.value = {
        prodPlanId: '',
        saleOrderId: '',
        productId: '',
        qty: 0,
        planProdQty: 0,
        saleOrderCode: '',
        productName: '',
        unit: '',
        prodFlowCode: [],
        processIdList: [],
        deliveryDate: '',
        remark: '',
        detailList: [
          {
            materialStockId: '',
            qty: 0,
            spec: '',
            unit: '',
            materialCode: '',
            outboundStatus: 0,
            fluteType: '',
            crimpLine: '',
            materialName: ''
          }
        ]
      }
      emit('update:visible', false)
      break
    case 'open':
      menuParam.switchEditStatus(true)
      getProcessList()
      getMaterialList()
      saleTableData.value = []
      for (const element of props.checkData) {
        for (let index = 0; index < element.detailList.length; index++) {
          if (index === 0) {
            saleTableData.value.push({ ...element, ...element.detailList[index] })
          } else {
            saleTableData.value.push({ ...element, ...element.detailList[index], span: 0 })
          }
        }
      }
      break
    case 'cancel':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      emit('update:visible', false)
      break
    default:
      break
  }
}

const proFilter = (inputValue: string, option: SelectOptionData) => {
  return (
    (option.value as string)?.split('-')[1].includes(inputValue) ||
    option.label?.includes(inputValue)
  )
}
</script>
<style scoped>
.card-container {
  margin-bottom: 10px;
}
:deep(.arco-checkbox-label) {
  flex: 1;
}
:deep(.arco-select-option-checkbox) {
  width: 100%;
}
:deep(.arco-select-option-content) {
  width: 100%;
}
</style>
